﻿using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;

namespace SimpleWcf
{
    public class CustomServiceHostFactory : ServiceHostFactory
    {
        public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
        {
            var host = new ServiceHost(constructorString, baseAddresses);
             
            //make sure aspnet compatibility is set. 
            //(Don't REQUIRE the service to have [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] )
            var compatibility = EnsureBehavior<AspNetCompatibilityRequirementsAttribute>(host);
            compatibility.RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed;
            
            return host;
        }

        private static T EnsureBehavior<T>(ServiceHost host) where T : class, IServiceBehavior, new()
        {
            var serviceBehavior = host.Description.Behaviors.Find<T>();
            //add it if it doesn't exist
            if (serviceBehavior == null)
            {
                serviceBehavior = new T();
                host.Description.Behaviors.Add(serviceBehavior);
            }
            return serviceBehavior;
        }
    }
}